/**
 * @Description: 公交运行平台协议发送工具类.
 * @author tao.xie
 * @date 2019-08-21 16:12
*/
import { ajaxAsyncForOpenPlatform, UserBeanUtils, ajaxAsync } from 'vue-xiaobu-utils'

const MERCHANT_NO = window.MERCHANTNO// 商户号，全局配置

/**
 * 组装公共参数到业务请求体中，目前只有商户号（全局统一配置），用户的OPEN_ID(应用下唯一，APP后台登录返回)，UNION_ID（全局唯一，APP后台登录返回，当前版本UNION_ID不传）
 * @param sendObj
 * @returns {*}
 */
async function addPublicParamsToSendObj(sendObj) {
  sendObj['MERCHANT_NO'] = MERCHANT_NO
  let res = await getUserThirdInfo()
  sendObj['OPEN_ID'] = res.OPEN_ID || 'AJryEjBvYjeibQ3yAzIBrq2e'
  if (res.UNION_ID) {
    sendObj['UNION_ID'] = res.UNION_ID
  }
  return sendObj
}

/**
 * 获取用户的第三方登录信息
 * @returns {Promise<{OPEN_ID: *, UNION_ID: *}>}
 */
async function getUserThirdInfo() {
  // 如果当前用户信息中存在OPEN_ID和UNION_ID，则直接按返回
  if (UserBeanUtils.getUserInfo().OPEN_ID && UserBeanUtils.getUserInfo().UNION_ID) {
    return { OPEN_ID: UserBeanUtils.getUserInfo().OPEN_ID, UNION_ID: UserBeanUtils.getUserInfo().UNION_ID }
  } else {
    // 如果不存在，则单独走协议去获取并更新到缓存中
    let res = await ajaxAsync('/user/register/thirdy_info', {
      THIRDY_APP_ID: window.appid
    })
    let userbean = UserBeanUtils.getUserInfo()
    let openId = res.OPEN_ID
    let unionId = res.UNION_ID
    userbean.OPEN_ID = openId
    userbean.UNION_ID = unionId
    UserBeanUtils.setUserInfo(userbean)
    return { OPEN_ID: openId, UNION_ID: unionId }
  }
}

/**
 * 往公交运营平台发送豹纹
 * @param urlString 请求url
 * @param sendObj 请求的业务豹纹
 * @param autoExLvl 异常处理级别
 * @returns {Promise<void>}
 * @constructor
 */
async function AjaxForBusOpen(urlString, sendObj, autoExLvl = 0) {
  let obj = await addPublicParamsToSendObj(sendObj)
  return ajaxAsyncForOpenPlatform(urlString, obj, autoExLvl)
}

export default AjaxForBusOpen
